<template>
    <div :class="propJson.editFlag ? 'formContainer' : 'formContainerCommon'">
        <el-form v-if="reloadFlag" :model="containerForm" :rules="componentRules" style="width: 100%" ref="formRef">
            <el-form-item v-if="!propJson.editFlag" :label="itemInfo.label" :label-width="propJson.labelLength" :prop="itemInfo.labelEn"  class="itemClassCommon"
                          v-for="itemInfo in sourceFormList" :key="itemInfo.id">
                <component :is="itemInfo.component" :propJson="itemInfo.propJson" :commonParam="commonParam" style="width: 100%">
                    <template v-slot:[itemSlot.slotName]="slotProps" v-for="itemSlot in slotList">
                        <slot :name="itemSlot.slotName" :slotProps="slotProps"></slot>
                    </template>
                </component>
            </el-form-item>

            <draggable v-if="propJson.editFlag"
                       :list="propJson.list"
                       animation="300"
                       :force-fallback="true"
                       :group="{name:'lowcode'}"
                       item-key="id"
            >
                <template #item="{ element }">
                    <el-form-item class="itemClass" :label="element.label" :prop="element.labelEn" :label-width="propJson.labelLength" :computeIsShow="computeIsShow">
                        <component :is="element.component" :propJson="element.propJson" v-if="itemFlag" :commonParam="commonParam" @click.stop="" @dblclick.stop="changeComponentInfo(element)" style="width: 100%"/>
                        <component is="CloseCircleOutlined" class="closeClass" @click.stop="" @dblclick.stop="deleteComponent(element)"/>
                    </el-form-item>
                </template>
            </draggable>

            <div class="formSubmitButton">
                <el-button v-if="propJson.showButtons.includes('Cancel')" @click="cancelSubmit()">取消</el-button>
                <el-button v-if="propJson.showButtons.includes('Reset')" @click="resetForm()">重置</el-button>
                <el-button type="primary" :loading="submitLoading" v-if="propJson.showButtons.includes('Submit')" @click="submitForm()">提交</el-button>
            </div>
        </el-form>
    </div>
</template>

<script>
import draggable from "vuedraggable";
import {deepCopy} from "@/utils/tagCreate";
import {getCommonParamObj} from "@/utils/commonParamUtil";
import {ElNotification} from "element-plus";
import {doThirdServiceAction} from "@/request/lowcode/thirdService";
import {getFromAssociationFlag} from "@/request/lowcode/formDataAssociation";

export default {
    name: "GlobalFormComponent",
    props: ['propJson', 'commonParam'],
    data() {
        return {
            containerForm: {},
            itemFlag: true,
            submitLoading: false,
            reloadFlag: true,
            sourceFormList: []
        }
    },
    components: {
        draggable
    },
    methods: {
        changeComponentInfo(element) {
            this.$store.state.currentDrawer = element.drawerComponent;
            this.$store.state.currentDrawerElementId = element.id;
            this.$store.state.currentDrawerTitle = element.title;
            let copyJson = deepCopy(element.propJson)
            this.$store.commit('changeLowCodeDrawerJsonInfo', copyJson)
            this.$store.state.isShowDrawer = true;
            this.$store.state.lowCodeComponentList = this.propJson.list
        },
        deleteComponent(element) {
            let index = -1;
            // 遍历当前列表，删除元素ID对应的数据
            for (let i = 0; i < this.propJson.list.length; i++) {
                if (this.propJson.list[i].id === element.id) {
                    index = i;
                }
            }
            if (index >= 0) {
                this.propJson.list.splice(index, 1);
            }
        },
        async cancelSubmit() {
            // 定义一个标志位，后续同步执行
            let awaitObj = {flag: false, res: true}
            await doThirdServiceAction(this.propJson.formCancelAction, awaitObj, this.commonParam, ()=>{}, ()=>{}, null);
        },
        submitForm() {
            this.saveLoading = true
            let formEl = this.$refs['formRef']
            if (!formEl) return
            formEl.validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true
                    // 定义一个标志位，后续同步执行
                    let awaitObj = {flag: false, res: true}
                    await doThirdServiceAction(this.propJson.formSubmitAction, awaitObj, this.commonParam, ()=>{}, ()=>{}, null);
                    this.submitLoading = false
                    if (awaitObj.res) {
                        ElNotification({
                            title: 'Success',
                            message: "成功",
                            type: 'success'
                        });
                    } else {
                        ElNotification({
                            title: 'Error',
                            message: "失败",
                            type: 'error'
                        });
                    }
                }
            })
        },
        resetForm() {

        },
        computeIsShow() {
            let formList = this.propJson.list;
            let tempList = [];
            for (let index = 0; index < formList.length; index++) {
                let formInfo = formList[index];
                let formPropJson = formInfo.propJson;
                if (!formPropJson.ruleInfo || !formPropJson.ruleInfo.ruleInfoList || formPropJson.ruleInfo.ruleInfoList.length === 0) {
                    tempList.push(formInfo);
                    continue;
                }
                let res = getFromAssociationFlag(formPropJson.ruleInfo, this.commonParam);
                if (res) {
                    tempList.push(formInfo);
                }
            }
            this.sourceFormList = tempList;
            this.reloadFlag = false;
            this.reloadFlag = true;
        }
    },
    computed: {
        componentRules() {
            let res = {}
            let itemList = this.propJson.list;
            for (let i = 0; i < itemList.length; i++) {
                let itemInfo = itemList[i];
                if (itemInfo.isMust) {
                    // 必填的字段需要添加校验对象
                    res[itemInfo.labelEn] = [{ required: true, message: `${itemInfo.mustTipContent}`, trigger: 'blur' }];
                }
            }
            // 设置containerForm
            for (let i = 0; i < itemList.length; i++) {
                let itemInfo = itemList[i];
                if (itemInfo.isMust) {
                    // 将绑定的参数对象设置到
                    let commonParamList = this.commonParam;
                    for (let j = 0; j < commonParamList.length; j++) {
                        let commonParamInfo = commonParamList[j];
                        if (commonParamInfo.variableName === itemInfo.propJson.bindVariable) {
                            this.containerForm[itemInfo.labelEn] = commonParamInfo.variableValue
                        }
                    }
                }
            }
            return res;
        },
        slotList() {
            let res = getCommonParamObj(this.commonParam, "templateSlotInfo")
            return res.variableValue;
        }
    },
    watch: {
        commonParam: {
            handler(newVal, oldVal) {
                this.computeIsShow();
            },
            deep: true
        }
    },
    created() {
        this.computeIsShow();
    }
}
</script>

<style scoped lang="less">
.formContainer {
    width: 96%;
    padding-left: 2%;
    padding-right: 2%;
    transition: box-shadow 0.3s ease;
    //去除光标
    caret-color: transparent;
    overflow: auto;
    .itemClass {
        position: relative;
        transition: box-shadow 0.3s ease;
        margin-bottom: 0.3%;
        .closeClass {
            display: none;
        }
    }
    .itemClassCommon {
        position: relative;
        transition: box-shadow 0.3s ease;
        margin-bottom: 0.3%;
        .closeClass {
            display: none;
        }
    }
    .itemClass:hover {
        cursor: pointer;
        box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.5);
        .closeClass {
            position: absolute;
            color: #e76565;
            top: 2px;
            right: 2px;
            display: block;
        }
    }
}
.formContainer:hover {
    cursor: pointer;
}

.formContainerCommon {
    width: 96%;
    padding-left: 2%;
    padding-right: 2%;
    .itemClass {
        margin-bottom: 0.3%;
    }
}

.formSubmitButton {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>